package org.opens.javaskill.thread.demo.myLock;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

/**
 * @Date 2020/8/15 15:08
 * @Created by 99126
 */
public class BooleanLock implements Lock {

    // 如果这个值为true表示这个锁正在被使用, 反之表示未被使用, 初始为false
    private boolean initValue;

    private Collection<Thread> blockedThread = new ArrayList<>();

    private Thread currentThread;

    public BooleanLock() {
        this.initValue = false;
    }

    @Override
    public synchronized void lock() throws InterruptedException {
        while(initValue) {
            blockedThread.add(Thread.currentThread());
            this.wait();
        }

        blockedThread.remove(Thread.currentThread());
        this.initValue = true;
        this.currentThread = Thread.currentThread();
    }

    @Override
    public synchronized void lock(long mills) throws InterruptedException, TimeOutException {
        if ( mills <= 0 ) {
            lock();
        }
        long hasRemaining = mills;
        long endTime = System.currentTimeMillis() + mills;
        while (initValue) {
            if ( hasRemaining <= 0 ) {
                throw new TimeOutException(Thread.currentThread().getName() + "Time out");
            }
            blockedThread.add(Thread.currentThread());
            this.wait(mills);
            hasRemaining = endTime - System.currentTimeMillis();
        }
        this.initValue = true;
        this.currentThread = Thread.currentThread();
    }

    @Override
    public synchronized void unLock() {
        if ( Thread.currentThread() == currentThread ) {
            this.initValue = false;
            System.out.println(Thread.currentThread().getName() + " unLock end.");
            this.notifyAll();
        }
    }

    @Override
    public Collection<Thread> getBlockedThread() {
        return Collections.unmodifiableCollection(blockedThread);
    }

    @Override
    public int getBlockedThreadSize() {
        return blockedThread.size();
    }
}
